package com.qeebu.SMSManagerClient.smsList;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.qeebu.SMSManagerClient.util.UtilMethod;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.view.View;

/**
 * 
 * <一句话功能简述>异步加载短信对话
 * <功能详细描述>
 * 
 * @author  johnxie
 * @version  [版本号, 2012-9-12]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */

class ReadConversionSMSAsyncTask extends AsyncTask<String, Integer, List<ConversionSMSItem>>{
    
    private Context context; 
    
    public static final Uri MMSSMS_FULL_CONVERSATION_URI = Uri.parse("content://mms-sms/conversations");
    public static final Uri CONVERSATION_URI = MMSSMS_FULL_CONVERSATION_URI.buildUpon().appendQueryParameter("simple", "true").build();
   
    private static final int ID = 0;
    private static final int DATE = 1;
    private static final int MESSAGE_COUNT = 2;
    private static final int RECIPIENT_IDS = 3;
    private static final int SNIPPET = 4;
    private static final int HAS_ATTACHMENT = 8;
    
    public static final Uri MMSSMS_CANONICAL_ADDRESSES_URI = Uri.parse("content://mms-sms/canonical-addresses");
    
    private List<ConversionSMSItem> smsList = new ArrayList<ConversionSMSItem>();


    private static final String[] ALL_THREADS_PROJECTION = {
        "_id", "date", "message_count", "recipient_ids",
        "snippet", "snippet_cs", "read", "error", "has_attachment"
    };

    private static final String[] CANONICAL_ADDRESSES = {
        "_id=?", "addresses"
    };
    
    public ReadConversionSMSAsyncTask(Context ctx)
    {
        context = ctx;
    }
    
    @Override
    protected List<ConversionSMSItem> doInBackground(String... params) {
        Cursor cursor_contacts = ((ConversionSMSListActivity)context).getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{
                            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER
        }, null, null, null);
        while(cursor_contacts.moveToNext()){
            String name = cursor_contacts.getString(cursor_contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = cursor_contacts.getString(cursor_contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            int len = phoneNumber.length();
            if(len>11)
                phoneNumber = phoneNumber.substring(len-11, len);
            /*从CONTENT_URI中读取所有的”联系号码-联系人名称"并存入UI线程中map中*/
            UtilMethod.getContact().put(phoneNumber, name);   
        }
        cursor_contacts.close();        
        
        /*从content://mms-sms/conversations中读取所有的短信对话，并将对话号码转换为对话人名称后放入到主线程短信列表中，以便显示*/
        Cursor cursor = context.getContentResolver().query(CONVERSATION_URI, ALL_THREADS_PROJECTION, null, null, null);
        Calendar calendar = Calendar.getInstance();
        while (cursor.moveToNext()) {
            try {
                ConversionSMSItem smsItem = new ConversionSMSItem();
                long id = cursor.getLong(ID);
                long date = cursor.getLong(DATE);
                Long msgCount = cursor.getLong(MESSAGE_COUNT);
                String recipIDs = cursor.getString(RECIPIENT_IDS);
                String snippet = cursor.getString(SNIPPET);
                //long snippetCS = cursor.getLong(SNIPPET_CS);
                //long read = cursor.getLong(READ);
                //long error = cursor.getLong(ERROR);
                long hasAttach = cursor.getLong(HAS_ATTACHMENT);
                Cursor cursorNum = context.getContentResolver().query(MMSSMS_CANONICAL_ADDRESSES_URI, 
                                    CANONICAL_ADDRESSES, "_id=?", new String[]{recipIDs}, null);
                //String num =  cursorNum.getString(0);
                cursorNum.moveToNext();
                String num1 =  cursorNum.getString(1);
                String name = UtilMethod.getName(num1);    
                
                if(hasAttach != 0){
                    continue;
                }
                Date fDate = new Date(date);
                calendar = Calendar.getInstance();
                calendar.setTime(fDate);
                smsItem.setId(id);
                smsItem.setDate(calendar.get(Calendar.YEAR)+"年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日");
                smsItem.setCount(msgCount.toString());
                smsItem.setBody(snippet);
                smsItem.setPhoneNum(name);
                smsList.add(smsItem);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        cursor.close();
        return smsList;
    }
    
    @Override
    protected void onPostExecute(List<ConversionSMSItem> list) {
        ((ConversionSMSListActivity)context).setSmsList(list);
        ((ConversionSMSListActivity)context).setAdapter();
        /*使进度条消失*/
        ((ConversionSMSListActivity)context).getProgressBar().setVisibility(View.GONE);
    }
}
